package com.linjiahao.nettyGateway.serverListener;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.linjiahao.nettyGateway.cluster.ClusterManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


@Component
@Slf4j
public class RegistrationCenterChangeEventListener implements EventListener {



    @Value("${spring.cloud.nacos.discovery.server-addr}")
    private String discoveryServerListList;

    @Value("${server.listener.name}")
    private String serverListenerName;


    @Autowired
    private ClusterManager clusterManager;

    private NamingService namingService;


    /**
     * key serverId  value 服务实例
     */

    public RegistrationCenterChangeEventListener() {

    }

    @Override
    @PostConstruct
    public void addListener() {

        try {
            this.namingService = NamingFactory.createNamingService(discoveryServerListList);
            namingService.subscribe(serverListenerName, event -> {
                log.info(event.toString());
                if (event instanceof NamingEvent) {
                    NamingEvent namingEvent = (NamingEvent) event;
                    log.info("- - - - - - - - - 监听到服务实例【" + serverListenerName + "】变化事件为{} - - - - - - - - - ",namingEvent.getEventType());
                    clusterManager.refreshNettyServer(namingEvent.getInstances());
                }
            });
        } catch (NacosException e) {
           log.error("刷新nacos监听{}服务异常:{}",serverListenerName,e);
        }
    }


}
